package com.luyuan.crm.member.web.validator;

import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.ValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Customer;
import com.luyuan.crm.member.service.CustomerService;
import com.ruijie.util.StringUtils;

@Component("customerMoblieValidator")
public class CustomerMoblieValidator implements Validator {

    @Resource(name = "customerService")
    private CustomerService customerService;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String oldValue = (String) ((ValueHolder) component).getValue();
        String mobile = (String) value;

        if (oldValue != null && mobile.equals(oldValue)) {
            // 值没有发生改变，不校验
            return;
        }

        if (StringUtils.isNullOrEmpty(mobile)) {
            return;
        }

        Customer customer = customerService.getByMobile(mobile);
        if (customer != null) {
            throw new ValidatorException(new FacesMessage("该手机号已经存在！"));
        }
    }
}
